#include <REGX52.H>
#include "Delay.h"

unsigned char Key_KeyNumber;


unsigned char Key()
{
	unsigned char Temp=0;
	Temp = Key_KeyNumber;
	Key_KeyNumber = 0;
	return Temp;
}

/**
  * @brief  获取独立按键键码
  * @param  无
  * @retval 按下按键的键码，范围1~4，无按下为0
  */
unsigned char Key_GetState()
{
		//按下P3_1为0，松开为1,这个函数为谁按下返回几，不按返回0
		unsigned char KeyNumber=0;
	
	P1=0xFF;
	P1_3=0;
	if(P1_7==0){KeyNumber=1;}
	if(P1_6==0){KeyNumber=5;}
	if(P1_5==0){KeyNumber=9;}
	if(P1_4==0){KeyNumber=13;}
	
	P1=0xFF;
	P1_2=0;
	if(P1_7==0){KeyNumber=2;}
	if(P1_6==0){KeyNumber=6;}
	if(P1_5==0){KeyNumber=10;}
	if(P1_4==0){KeyNumber=14;}
	
	P1=0xFF;
	P1_1=0;
	if(P1_7==0){KeyNumber=3;}
	if(P1_6==0){KeyNumber=7;}
	if(P1_5==0){KeyNumber=11;}
	if(P1_4==0){KeyNumber=15;}
	
	P1=0xFF;
	P1_0=0;
	if(P1_7==0){KeyNumber=4;}
	if(P1_6==0){KeyNumber=8;}
	if(P1_5==0){KeyNumber=12;}
	if(P1_4==0){KeyNumber=16;}
	return KeyNumber;
}

//在中断中隔一段调用就可以拥有一个中断
void Key_Loop(void)
{
		//每隔20ms检测一次也可以避免抖动，而且使用中断
		static unsigned char NowState,LastState;
		LastState = NowState;
		NowState = Key_GetState();
	
		//通过改变LastState和NowState组合可以实现多种按键方式，如按下检测，长按检测等等
		if(LastState == 1 && NowState == 0)
		{
			Key_KeyNumber = 1;
		}
		if(LastState == 2 && NowState == 0)
		{
			Key_KeyNumber = 2;
		}
		if(LastState == 3 && NowState == 0)
		{
			Key_KeyNumber = 3;
		}
//		if(LastState == 4 && NowState == 0)
//		{
//			Key_KeyNumber = 4;
//		}		
		if(LastState == 5 && NowState == 0)
		{
			Key_KeyNumber = 4;
		}
		if(LastState == 6 && NowState == 0)
		{
			Key_KeyNumber = 5;
		}
		if(LastState == 7 && NowState == 0)
		{
			Key_KeyNumber = 6;
		}
//		if(LastState == 8 && NowState == 0)
//		{
//			Key_KeyNumber = 8;
//		}
//		if(LastState == 9 && NowState == 0)
//		{
//			Key_KeyNumber = 9;
//		}
//		if(LastState == 10 && NowState == 0)
//		{
//			Key_KeyNumber = 10;
//		}
//		if(LastState == 11 && NowState == 0)
//		{
//			Key_KeyNumber = 11;
//		}
//		if(LastState == 12 && NowState == 0)
//		{
//			Key_KeyNumber = 12;
//		}
		if(LastState == 13 && NowState == 0)
		{
			Key_KeyNumber = 7;
		}
		if(LastState == 14 && NowState == 0)
		{
			Key_KeyNumber = 8;
		}		
		if(LastState == 15 && NowState == 0)
		{
			Key_KeyNumber = 9;
		}
//		if(LastState == 16 && NowState == 0)
//		{
//			Key_KeyNumber = 16;
//		}
}